<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>
    // 获取随机数 => 异步版,返回Promise实例(pending) 指定时间之后可以变为fulfilled/rejected
    function getNumAsync(num, delay = 0, isFulfilled = true) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                isFulfilled ? resolve(num) : reject(num);
            }, delay);
        })
    }



    // Promise的链式操作  => 多个异步操作之间相互依赖 (后面的请求需要依赖前面的结果)
    // T = T1 + T2 + T3; 
    var p = getNumAsync(1, 2000); // 2s
    p.then((res) => {
        console.log("fulfilled", res);
        return getNumAsync(2, 1000) // 1s
    }).then((res) => {
        console.log("fulfilled", res);
        return getNumAsync(3, 3000); // 3s
    }).then(res => {
        console.log("fulfilled", res);
    }).catch(err => {
        console.log("rejected", err);
    })

    // 如果多个异步操作之间不相互依赖,同时启动多个异步操作,按顺序返回结果
    // var p1 = getNumAsync(1, 2000); // 2s
    // var p2 = getNumAsync(2, 1000); // 1s
    // var p3 = getNumAsync(3, 3000); // 3s

    // p1.then((res) => {
    //     console.log("fulfilled", res);
    //     return p2;
    // }).then((res) => {
    //     console.log("fulfilled", res);
    //     return p3; // 3s
    // }).then(res => {
    //     console.log("fulfilled", res);
    // }).catch(err => {
    //     console.log("rejected", err);
    // })


    // 上述代码,同时启动三个异步操作(全部都有结果,最多耗时3s) =>  p1状态改变需要2s => 执行then方法,此时p2状态已经改变, 继续向后调用then()方法, 再等待1s,p3的状态也会改变  => 总共耗3s






</script>

</html>